package org.mog.common.controller;

import entity.resullt.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mog.file.service.FileStorageService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import utils.AliOssUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/common")
@Api(tags = "通用接口")
@Slf4j
@RequiredArgsConstructor
public class CommonController {
    private final AliOssUtils aliOssUtils;
    private final FileStorageService fileStorageService;

    /**
     * 文件上传
     *
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file.getOriginalFilename());

        try {
            String[] fileNameSplit = file.getOriginalFilename().split("\\.");
            String suffix = fileNameSplit[fileNameSplit.length - 1];

            //生成随机文件名
            String str = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = str + "." + suffix;
            log.info(fileName);

            //获取流
            InputStream is = new ByteArrayInputStream(file.getBytes());

            //上传获取文件路径
            String url = fileStorageService.uploadImgFile("", fileName, is);
            log.info("上传成功：{}", url);
            return Result.success(url);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
        }
        return Result.error("文件上传失败");
    }
}
